<template>
  <div class="memory-management">
    <el-card>
      <template #header>
        <div class="header-content">
          <span>AI记忆管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="showCreateDialog">
              <el-icon><Plus /></el-icon>
              新增记忆
            </el-button>
            <el-button type="info" @click="showStatistics">
              <el-icon><DataAnalysis /></el-icon>
              统计信息
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索筛选区域 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="场景名称">
            <el-input v-model="searchForm.scene_name" placeholder="场景名称" clearable style="width: 150px" />
          </el-form-item>
          <el-form-item label="智能体名称">
            <el-input v-model="searchForm.agent_name" placeholder="智能体名称" clearable style="width: 150px" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 120px">
              <el-option label="临时" :value="1" />
              <el-option label="当天" :value="2" />
              <el-option label="永久" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="重要程度">
            <el-select v-model="searchForm.importance_level" placeholder="重要程度" clearable style="width: 120px">
              <el-option label="很低" :value="1" />
              <el-option label="低" :value="2" />
              <el-option label="中等" :value="3" />
              <el-option label="高" :value="4" />
              <el-option label="很高" :value="5" />
            </el-select>
          </el-form-item>
          <el-form-item label="标签">
            <el-input v-model="searchForm.tags" placeholder="标签搜索" clearable style="width: 120px" />
          </el-form-item>
          <el-form-item label="关键词">
            <el-input v-model="searchForm.keyword" placeholder="内容关键词" clearable style="width: 150px" />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 350px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 批量操作区域 -->
      <div class="batch-actions" v-if="selectedRows.length > 0">
        <el-alert
          :title="`已选择 ${selectedRows.length} 条记录`"
          type="info"
          show-icon
          :closable="false"
        />
        <div class="batch-buttons">
          <el-button type="warning" @click="showBatchUpdateDialog">
            <el-icon><Edit /></el-icon>
            批量更新
          </el-button>
          <el-button type="danger" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
          <el-button type="danger" @click="showBatchDeleteByDateDialog">
            <el-icon><Calendar /></el-icon>
            按日期删除
          </el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
        height="500"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="scene_name" label="场景名称" width="120" show-overflow-tooltip />
        <el-table-column prop="agent_name" label="智能体名称" width="120" show-overflow-tooltip />
        <el-table-column prop="his_text" label="消息内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="importance_level" label="重要程度" width="100">
          <template #default="{ row }">
            <el-rate
              v-model="row.importance_level"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            />
          </template>
        </el-table-column>
        <el-table-column prop="tags" label="标签" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <div v-if="row.tags">
              <el-tag
                v-for="tag in getTags(row.tags)"
                :key="tag"
                size="small"
                style="margin-right: 5px;"
              >
                {{ tag }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑记忆' : '新增记忆'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="场景名称" prop="scene_name">
              <el-input v-model="formData.scene_name" placeholder="请输入场景名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="智能体名称" prop="agent_name">
              <el-input v-model="formData.agent_name" placeholder="请输入智能体名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="对话ID" prop="session_id">
              <el-input v-model="formData.session_id" placeholder="请输入对话ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户ID" prop="user_id">
              <el-input v-model="formData.user_id" placeholder="请输入用户ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="消息内容" prop="his_text">
          <el-input
            v-model="formData.his_text"
            type="textarea"
            :rows="4"
            placeholder="请输入消息内容"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="选择状态">
                <el-option label="临时" :value="1" />
                <el-option label="当天" :value="2" />
                <el-option label="永久" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="重要程度" prop="importance_level">
              <el-rate v-model="formData.importance_level" show-text />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="标签">
          <el-input
            v-model="formData.tags"
            placeholder="多个标签用英文逗号分隔，如：重要,项目,客户"
            maxlength="255"
          />
        </el-form-item>
        <el-form-item label="标注内容">
          <el-input
            v-model="formData.annotation"
            type="textarea"
            :rows="3"
            placeholder="请输入标注内容"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="记忆详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{ viewData.id }}</el-descriptions-item>
        <el-descriptions-item label="场景名称">{{ viewData.scene_name }}</el-descriptions-item>
        <el-descriptions-item label="智能体名称">{{ viewData.agent_name }}</el-descriptions-item>
        <el-descriptions-item label="对话ID">{{ viewData.session_id }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ viewData.user_id }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(viewData.status)">
            {{ getStatusText(viewData.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="重要程度">
          <el-rate :model-value="viewData.importance_level" disabled show-text />
        </el-descriptions-item>
        <el-descriptions-item label="标签">
          <div v-if="viewData.tags">
            <el-tag
              v-for="tag in getTags(viewData.tags)"
              :key="tag"
              size="small"
              style="margin-right: 5px;"
            >
              {{ tag }}
            </el-tag>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(viewData.create_time) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDateTime(viewData.update_time) }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions :column="1" border style="margin-top: 20px;">
        <el-descriptions-item label="消息内容">
          <div style="white-space: pre-wrap; word-break: break-all;">{{ viewData.his_text }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="标注内容" v-if="viewData.annotation">
          <div style="white-space: pre-wrap; word-break: break-all;">{{ viewData.annotation }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 批量更新对话框 -->
    <el-dialog v-model="batchUpdateDialogVisible" title="批量更新" width="500px">
      <el-form :model="batchUpdateForm" label-width="100px">
        <el-form-item label="状态">
          <el-select v-model="batchUpdateForm.status" placeholder="选择状态" clearable>
            <el-option label="临时" :value="1" />
            <el-option label="当天" :value="2" />
            <el-option label="永久" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="重要程度">
          <el-rate v-model="batchUpdateForm.importance_level" show-text clearable />
        </el-form-item>
        <el-form-item label="标签">
          <el-input
            v-model="batchUpdateForm.tags"
            placeholder="多个标签用英文逗号分隔"
            maxlength="255"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchUpdateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchUpdate" :loading="batchUpdateLoading">
            批量更新
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 按日期批量删除对话框 -->
    <el-dialog v-model="batchDeleteByDateDialogVisible" title="按日期批量删除" width="500px">
      <el-form :model="batchDeleteByDateForm" label-width="100px">
        <el-form-item label="时间范围" required>
          <el-date-picker
            v-model="batchDeleteByDateForm.dateRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态筛选">
          <el-select v-model="batchDeleteByDateForm.status" placeholder="选择状态" clearable>
            <el-option label="临时" :value="1" />
            <el-option label="当天" :value="2" />
            <el-option label="永久" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="场景名称">
          <el-input v-model="batchDeleteByDateForm.scene_name" placeholder="可选，筛选特定场景" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchDeleteByDateDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleBatchDeleteByDate" :loading="batchDeleteByDateLoading">
            确认删除
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 统计信息对话框 -->
    <el-dialog v-model="statisticsDialogVisible" title="记忆统计信息" width="800px">
      <div v-if="statisticsData">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic title="总记忆数量" :value="statisticsData.total_count" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="临时记忆" :value="statisticsData.temporary_count" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="当天记忆" :value="statisticsData.daily_count" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="永久记忆" :value="statisticsData.permanent_count" />
          </el-col>
        </el-row>
        
        <div style="margin-top: 30px;">
          <h4>重要程度分布</h4>
          <el-row :gutter="20">
            <el-col :span="4" v-for="(count, level) in statisticsData.importance_distribution" :key="level">
              <el-statistic :title="`${level}级重要`" :value="count" />
            </el-col>
          </el-row>
        </div>

        <div style="margin-top: 30px;">
          <h4>最近7天活动</h4>
          <el-table :data="statisticsData.recent_activity" size="small">
            <el-table-column prop="date" label="日期" />
            <el-table-column prop="count" label="新增数量" />
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Refresh,
  Edit,
  Delete,
  View,
  DataAnalysis,
  Calendar
} from '@element-plus/icons-vue'

// 类型定义
interface MemoryItem {
  id: number
  scene_name: string
  agent_name: string
  session_id: string
  user_id: string
  his_text: string
  status: number
  importance_level: number
  tags?: string
  annotation?: string
  create_time: string
  update_time?: string
  extra_info?: any
}

interface SearchForm {
  scene_name: string
  agent_name: string
  session_id: string
  user_id: string
  status: number | null
  importance_level: number | null
  tags: string
  keyword: string
  dateRange: string[]
}

interface FormData {
  id?: number
  scene_name: string
  agent_name: string
  session_id: string
  user_id: string
  his_text: string
  status: number
  importance_level: number
  tags: string
  annotation: string
}

interface BatchUpdateForm {
  status: number | null
  importance_level: number | null
  tags: string
}

interface StatisticsData {
  total_count: number
  temporary_count: number
  daily_count: number
  permanent_count: number
  importance_distribution: Record<number, number>
  recent_activity: Array<{ date: string; count: number }>
}

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const batchUpdateLoading = ref(false)
const batchDeleteByDateLoading = ref(false)
const tableData = ref<MemoryItem[]>([])
const selectedRows = ref<MemoryItem[]>([])
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const batchUpdateDialogVisible = ref(false)
const batchDeleteByDateDialogVisible = ref(false)
const statisticsDialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()
const statisticsData = ref<StatisticsData | null>(null)

// 搜索表单
const searchForm = reactive<SearchForm>({
  scene_name: '',
  agent_name: '',
  session_id: '',
  user_id: '',
  status: null,
  importance_level: null,
  tags: '',
  keyword: '',
  dateRange: []
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 表单数据
const formData = reactive<FormData>({
  scene_name: '',
  agent_name: '',
  session_id: '',
  user_id: '',
  his_text: '',
  status: 1,
  importance_level: 3,
  tags: '',
  annotation: ''
})

// 查看详情数据
const viewData = reactive<MemoryItem>({
  id: 0,
  scene_name: '',
  agent_name: '',
  session_id: '',
  user_id: '',
  his_text: '',
  status: 1,
  importance_level: 3,
  tags: '',
  annotation: '',
  create_time: '',
  update_time: '',
  extra_info: null
})

// 批量更新表单
const batchUpdateForm = reactive<BatchUpdateForm>({
  status: null,
  importance_level: null,
  tags: ''
})

// 按日期批量删除表单
const batchDeleteByDateForm = reactive({
  dateRange: [] as string[],
  status: null as number | null,
  scene_name: ''
})

// 表单验证规则
const formRules = {
  scene_name: [{ required: true, message: '请输入场景名称', trigger: 'blur' }],
  agent_name: [{ required: true, message: '请输入智能体名称', trigger: 'blur' }],
  session_id: [{ required: true, message: '请输入对话ID', trigger: 'blur' }],
  user_id: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  his_text: [{ required: true, message: '请输入消息内容', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  importance_level: [{ required: true, message: '请选择重要程度', trigger: 'change' }]
}

// API调用方法
const api = {
  async getMemoryList(params: any) {
    const response = await fetch(`/api/memory/?${new URLSearchParams(params)}`)
    const result = await response.json()
    
    if (!response.ok) {
      throw new Error(result.detail || `HTTP ${response.status}: ${response.statusText}`)
    }
    
    return result
  },

  async createMemory(data: any) {
    const response = await fetch('/api/memory/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    })
    const result = await response.json()
    
    if (!response.ok) {
      throw new Error(result.detail || `HTTP ${response.status}: ${response.statusText}`)
    }
    
    return result
  },

  async updateMemory(id: number, data: any) {
    const response = await fetch(`/api/memory/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    })
    const result = await response.json()
    
    if (!response.ok) {
      throw new Error(result.detail || `HTTP ${response.status}: ${response.statusText}`)
    }
    
    return result
  },

  async deleteMemory(id: number) {
    const response = await fetch(`/api/memory/${id}`, {
      method: 'DELETE'
    })
    const result = await response.json()
    
    if (!response.ok) {
      throw new Error(result.detail || `HTTP ${response.status}: ${response.statusText}`)
    }
    
    return result
  },

  async batchUpdate(data: any) {
    const response = await fetch('/api/memory/batch_update', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    })
    const result = await response.json()
    
    if (!response.ok) {
      throw new Error(result.detail || `HTTP ${response.status}: ${response.statusText}`)
    }
    
    return result
  },

  async batchDelete(ids: number[]) {
    const response = await fetch('/api/memory/batch_delete', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ids })
    })
    const result = await response.json()
    
    if (!response.ok) {
      throw new Error(result.detail || `HTTP ${response.status}: ${response.statusText}`)
    }
    
    return result
  },

  async batchDeleteByDate(params: any) {
    const response = await fetch('/api/memory/batch_delete_by_date', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(params)
    })
    
    const result = await response.json()
    
    if (!response.ok) {
      throw new Error(result.detail || `HTTP ${response.status}: ${response.statusText}`)
    }
    
    return result
  },

  async getStatistics(params: any = {}) {
    const response = await fetch(`/api/memory/statistics/overview?${new URLSearchParams(params)}`)
    const result = await response.json()
    
    if (!response.ok) {
      throw new Error(result.detail || `HTTP ${response.status}: ${response.statusText}`)
    }
    
    return result
  }
}

// 业务方法
const loadData = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...searchForm
    }

    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.start_time = searchForm.dateRange[0]
      params.end_time = searchForm.dateRange[1]
    }
    delete params.dateRange

    // 移除空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const result = await api.getMemoryList(params)
    tableData.value = result.items || []
    pagination.total = result.total || 0
  } catch (error: any) {
    ElMessage.error('加载数据失败：' + error.message)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  const keys = Object.keys(searchForm) as Array<keyof SearchForm>
  keys.forEach(key => {
    if (key === 'dateRange') {
      (searchForm[key] as string[]) = []
    } else if (key === 'status' || key === 'importance_level') {
      (searchForm[key] as number | null) = null
    } else {
      (searchForm[key] as string) = ''
    }
  })
  handleSearch()
}

const handleCurrentChange = () => {
  loadData()
}

const handleSizeChange = () => {
  pagination.page = 1
  loadData()
}

const handleSelectionChange = (rows: MemoryItem[]) => {
  selectedRows.value = rows
}

const showCreateDialog = () => {
  isEdit.value = false
  resetFormData()
  dialogVisible.value = true
}

const handleView = (row: MemoryItem) => {
  Object.assign(viewData, row)
  viewDialogVisible.value = true
}

const handleEdit = (row: MemoryItem) => {
  isEdit.value = true
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleDelete = async (row: MemoryItem) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记忆吗？', '确认删除', {
      type: 'warning'
    })
    
    await api.deleteMemory(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message)
    }
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    if (isEdit.value && formData.id) {
      await api.updateMemory(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      await api.createMemory(formData)
      ElMessage.success('创建成功')
    }

    dialogVisible.value = false
    loadData()
  } catch (error: any) {
    ElMessage.error((isEdit.value ? '更新' : '创建') + '失败：' + error.message)
  } finally {
    submitLoading.value = false
  }
}

const showBatchUpdateDialog = () => {
  resetBatchUpdateForm()
  batchUpdateDialogVisible.value = true
}

const handleBatchUpdate = async () => {
  try {
    batchUpdateLoading.value = true
    const data: any = {
      ids: selectedRows.value.map((row: MemoryItem) => row.id),
      ...batchUpdateForm
    }

    // 移除空值
    Object.keys(data).forEach(key => {
      if (data[key] === null || data[key] === '' || data[key] === undefined) {
        delete data[key]
      }
    })

    await api.batchUpdate(data)
    ElMessage.success('批量更新成功')
    batchUpdateDialogVisible.value = false
    loadData()
  } catch (error: any) {
    ElMessage.error('批量更新失败：' + error.message)
  } finally {
    batchUpdateLoading.value = false
  }
}

const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条记忆吗？`, '确认删除', {
      type: 'warning'
    })

    const ids = selectedRows.value.map((row: MemoryItem) => row.id)
    await api.batchDelete(ids)
    ElMessage.success('批量删除成功')
    loadData()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败：' + error.message)
    }
  }
}

const showBatchDeleteByDateDialog = () => {
  resetBatchDeleteByDateForm()
  batchDeleteByDateDialogVisible.value = true
}

const handleBatchDeleteByDate = async () => {
  try {
    if (!batchDeleteByDateForm.dateRange || batchDeleteByDateForm.dateRange.length !== 2) {
      ElMessage.error('请选择时间范围')
      return
    }

    await ElMessageBox.confirm('确定要删除指定时间范围内的记忆吗？此操作不可恢复！', '确认删除', {
      type: 'warning'
    })

    batchDeleteByDateLoading.value = true
    const params: any = {
      start_date: String(batchDeleteByDateForm.dateRange[0]),
      end_date: String(batchDeleteByDateForm.dateRange[1])
    }

    if (batchDeleteByDateForm.status !== null) {
      params.status = batchDeleteByDateForm.status
    }
    if (batchDeleteByDateForm.scene_name) {
      params.scene_name = batchDeleteByDateForm.scene_name
    }

    await api.batchDeleteByDate(params)
    ElMessage.success('按日期批量删除成功')
    batchDeleteByDateDialogVisible.value = false
    loadData()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('按日期批量删除失败：' + error.message)
    }
  } finally {
    batchDeleteByDateLoading.value = false
  }
}

const showStatistics = async () => {
  try {
    statisticsData.value = await api.getStatistics()
    statisticsDialogVisible.value = true
  } catch (error: any) {
    ElMessage.error('获取统计信息失败：' + error.message)
  }
}

// 工具方法
const resetFormData = () => {
  Object.assign(formData, {
    scene_name: '',
    agent_name: '',
    session_id: '',
    user_id: '',
    his_text: '',
    status: 1,
    importance_level: 3,
    tags: '',
    annotation: ''
  })
}

const resetBatchUpdateForm = () => {
  Object.assign(batchUpdateForm, {
    status: null,
    importance_level: null,
    tags: ''
  })
}

const resetBatchDeleteByDateForm = () => {
  Object.assign(batchDeleteByDateForm, {
    dateRange: [],
    status: null,
    scene_name: ''
  })
}

const getStatusText = (status: number): string => {
  const statusMap: Record<number, string> = { 1: '临时', 2: '当天', 3: '永久' }
  return statusMap[status] || '未知'
}

const getStatusType = (status: number): string => {
  const typeMap: Record<number, string> = { 1: 'info', 2: 'warning', 3: 'success' }
  return typeMap[status] || 'info'
}

const getTags = (tagsStr?: string): string[] => {
  return tagsStr ? tagsStr.split(',').map(tag => tag.trim()).filter(tag => tag) : []
}

const formatDateTime = (dateTime?: string): string => {
  return dateTime ? new Date(dateTime).toLocaleString() : '-'
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.memory-management {
  height: 100%;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.batch-actions {
  margin-bottom: 20px;
  padding: 15px;
  background: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-buttons {
  display: flex;
  gap: 10px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

.el-table {
  font-size: 14px;
}

.el-form-item {
  margin-bottom: 20px;
}

pre {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  max-height: 200px;
  overflow: auto;
}
</style> 